package com.ruoyi.match.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.match.job.service.HistoryMatchTaskOddsChangeService;
import com.ruoyi.match.job.service.HistoryMatchTaskService;
import com.ruoyi.match.match.domain.Match;
import com.ruoyi.match.match.domain.MatchCollectionDate;
import com.ruoyi.match.match.mapper.MatchMapper;
import com.ruoyi.match.utils.BrowserUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.openqa.selenium.WebDriver;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author sjz
 * @version 1.0.0
 * @desc
 * @date 2023/11/20 23:02
 **/

@Slf4j
@Component
@RequiredArgsConstructor
public class HistoryMatchTaskOddsChange {

    private final MatchMapper historyMatchMapper;
    private final HistoryMatchTaskOddsChangeService historyMatchTaskOddsChangeService;

    @XxlJob("historyMatchTaskOddsChange")
    private void process() throws IOException {
        Proxy proxy = null;
        Connection connectProx = Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
        try {
            String text = connectProx.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
                String[] split = text.split(":");
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(split[0], Integer.parseInt(split[1])));
            }
        }catch (Exception e){
            log.error("使用代理发生异常");
            connectProx =  Jsoup.connect("http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions=&gm=4");
            String text = connectProx.get().body().text();
            if(StrUtil.isNotBlank(text)){
                log.info("代理IP:"+text);
                String[] split = text.split(":");
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(split[0], Integer.parseInt(split[1])));
            }
        }

        List<Match> matches = historyMatchMapper.selectList(Wrappers.<Match>lambdaQuery().isNull(Match::getRemark).isNotNull(Match::getMatchDate));
        if(CollUtil.isNotEmpty(matches)) {
            try {
                for (Match match : matches) {
                    historyMatchTaskOddsChangeService.getOddsChangeList(match,proxy);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
